<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mention Example</title>
<style>
  .editable {
    border: 1px solid #ccc;
    /* min-height: 100px; */
    padding: 10px;
  }
  .mention {
    background-color: #e0e0e0;
    font-weight: bold;
    /* display: inline-block; */
  }
</style>
</head>
<body>

<div class="editable" contenteditable="true"></div>

<script>
  const editableDiv = document.querySelector('.editable');

  editableDiv.addEventListener('keydown', function(event) {
    if (event.key === '@') {
      event.preventDefault();
      const mentionSpan = document.createElement('span');
      mentionSpan.className = 'mention';
      mentionSpan.innerHTML = `<span>🍎</span>`;
      mentionSpan.contentEditable = false;
      mentionSpan.innerHTML = `&nbsp;${mentionSpan.innerHTML}&nbsp;`
      const selection = window.getSelection();
      const range = selection.getRangeAt(0);
      range.deleteContents();
      range.insertNode(mentionSpan);
      range.setStartAfter(mentionSpan);
      range.setEndAfter(mentionSpan);
      selection.removeAllRanges();
      selection.addRange(range);
    }
  });

  editableDiv.addEventListener('keyup', function(event) {
    // if (event.key === 'Backspace') {
    //   const selection = window.getSelection();
    //   const range = selection.getRangeAt(0);
    //   const startNode = range.startContainer;
    //   if (startNode.previousSibling && startNode.previousSibling.className === 'mention') {
    //     range.selectNode(startNode.previousSibling);
    //     range.deleteContents();
    //   }
    // }
  });
</script>

</body>
</html>
